package sp.dao;

import sp.dao.BaseDao;
import sp.dao.NovelDao;
import sp.dao.Page;
import sp.entity.Novel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class NovelDaoImpl extends BaseDao<Novel> implements NovelDao {
    @Override
    public Page<Novel> find(Map<String, String> params, int page, int row) {
        StringBuffer countSql = new StringBuffer("select count(1) from novel where 1=1");
        StringBuffer sql = new StringBuffer("select id, classId,name,author,description,chapterCount from novel where 1=1");
        StringBuffer cond = new StringBuffer();
        List<Object> values = new ArrayList<>();
        if(params!=null&&params.size()>0){
            if(params.containsKey("id")) {
                cond.append(" and id = ?");
                values.add(params.get("id"));
            }
            if(params.containsKey("classId")) {
                cond.append(" and classId = ?");
                values.add(params.get("classId"));
            }
            if(params.containsKey("name")) {
                cond.append(" and name like ?");
                values.add(params.get("name")+"%");
            }
            if(params.containsKey("author")) {
                cond.append(" and author like ?");
                values.add(params.get("author"));
            }
            countSql.append(cond);
            sql.append(cond);
        }
        sql.append(" order by id limit ?,?");
        return queryByPage(countSql.toString(),sql.toString(),values.toArray(),page,row);
    }

    @Override
    public void delete(String id) {
        super.executeUpdate("delete from novel where id = ?",new Object[]{id});
    }

    @Override
    public void addNovel(Novel novel) {
        super.executeUpdate("insert into novel(id,classId,name,author,description,chapterCount) values(?,?,?,?,?,?)"
                ,new Object[]{novel.getId(),novel.getClassId(),novel.getName(),novel.getAuthor(),novel.getDescription(),novel.getChapterCount()});
    }

    @Override
    public void updateNovel(Novel novel) {
        super.executeUpdate("update novel set name = ? , author = ?  , description = ? , chapterCount = ? where id = ? ",
                                new Object[]{novel.getName(),novel.getAuthor(),
                                novel.getDescription(),novel.getChapterCount(),
                                novel.getId()});
    }

    @Override
    public List<Novel> findAll() {
        StringBuffer sql = new StringBuffer("select id from novel");
        return query(sql.toString(),new Object[]{});
    }
}
